import tkinter,time,threading,random,queue
from package.Tk_grid import Tk_grid

import inspect
import ctypes
import os
#开启多线程客户端类 
class ThreadClient():  
    def __init__(self,conf):
        self.gui = Tk_grid()
        self.master = self.gui.tk
        self.mainMod = conf['mainMod']
        self.picPath= conf['shotFile']
        if(os.path.exists(self.picPath)):
            self.gui.loadPic1(self.picPath)
            self.gui.loadF1()
            self.gui.loadPic2(self.picPath)
            self.gui.loadF2()
        self.master.update()
        self.text = tkinter.Text(self.master, width=50, height=30)
        self.text.grid(row=1,column=1,sticky=tkinter.W)
        self.text.insert('1.0', '脚本启动中...')
        #tkinter.Button(self.master,text='开始脚本',command=self.endClient).grid(row=2,column=0,sticky=tkinter.W)
        tkinter.Button(self.master,text='关闭脚本',command=self.endClient).grid(row=2,column=1,sticky=tkinter.W)
        # e = tkinter.StringVar()
        # e.set('adb shell ip -f inet addr show wlan0')
        # tkinter.Entry(self.master,textvariable=e).grid(row=3)
        #开启队列
        self.queue= queue.Queue()
        #图形开关？
        self.running=True
        #开启工作子线程
        self.threadOne=threading.Thread(target=self.subThread)
        self.threadOne.start()
        print('开启子进程')
        #开启主进程
        self.mainThead()
    
        self.master.mainloop()
    def startSubThead(self):
        self.threadOne = threading.Thread(target=self.subThread)
        self.threadOne.start()
    def mainThead(self):
        #tk.after 图形延迟执行函数 after(delay_ms, callback=None, *args)   
        self.master.after(200,self.mainThead)
        #消费队列
        self.customerQueue()
        #判断开关
        if not self.running:
            self.running = 1
            #销毁图形界面
            self.master.destroy()
            #强制关闭子进程
            self.stop_thread(self.threadOne)
            #关闭窗口不关闭线程
            #self.threadOne.join()

    #消费队列
    def customerQueue(self):
        #返回队列的大小 
        while self.queue.qsize():  
            try:
            #Queue.get([block[,timeout]])删除并且返回队列里的一项。如果可选参数block是true，并且timeout是None，那么等到队列里面没有项时，会一直阻塞下去。如果block是true并且timeout为一个正数（单位是秒），那么在timeout秒之内没有可用的项获得，就会引发empty异常。如果block是false，那么不管timeout是多少，一旦没有可用项，就会引发空异常。
                data=self.queue.get(0)
                print(data)
                if "msg" in data:
                    #print(data['msg'])
                    self.text.insert('1.0','主线程msg:%s \n'%(data['msg']))
                if "stage" in data:
                    print("主线程:正在更新匹配图")
                    self.gui.loadPic1(data['stage'])
                    self.gui.loadF1()
                if "action" in data:
                    print("主线程:正在更新手机截图")
                    self.gui.loadPic2(data['action'])
                    self.gui.loadF2()
            except queue.Empty:  
                pass
    #生产队列
    def productQueue(self,res):
         self.queue.put(res)
    
    #工作子线程 例子
    def subThread(self):
        #随机休眠防止死锁
        rand=random.Random() 
        #判断开关 
        while self.running:
            #执行动作
            time.sleep(rand.random()*1.5)  
            AI = __import__(self.mainMod) 
            print("载入AI配置%s........" %(self.mainMod))
            #开启循环
            while True:
                #启动AI
                print("启动AI策略........")
                #获取模块中的类
                result = getattr(AI, self.mainMod)
                #实例化类
                r= result(self.queue)
                #调取方法
                res = r.Start()
                if res:
                   continue
                else:
                   print(res)
                   exit()
            #放入队列
            #self.productQueue(msg)
    #关闭开关
    def endClient(self):  
        self.running=False
        
    #强制关闭子进程
    def _async_raise(self,tid, exctype):
        """raises the exception, performs cleanup if needed"""
        tid = ctypes.c_long(tid)
        if not inspect.isclass(exctype):
            exctype = type(exctype)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            # """if it returns a number greater than one, you're in trouble,
            # and you should call it again with exc=NULL to revert the effect"""
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")
    #关闭进程
    def stop_thread(self,thread):
        self._async_raise(thread.ident, SystemExit)

#client=ThreadClient(subThead)   